


#include "client.h"

using namespace muduo;
using namespace muduo::net;

ProtoClient::ProtoClient(EventLoop *loop, const InetAddress &serverAddr)
        : loop_(loop),
          client_(loop, serverAddr, "ProtoClient") {
    client_.setConnectionCallback(
            std::bind(&ProtoClient::onConnection, this, _1));
    client_.setMessageCallback(
            std::bind(&ProtoClient::onMessage, this, _1, _2, _3));
    // client_.enableRetry();
}

void ProtoClient::connect() {
    client_.connect();
}

void ProtoClient::disconnect() {
    client_.stop();
    client_.disconnect();
}

void ProtoClient::sendMessage(string msg) {

    if (connection_) {
        connection_->send(msg);
        // codec_.send(get_pointer(connection_), msg);
    }
    // client_.connection()->if (client_.connection()->connected())
    // {
    //     client_.connection()->send(msg);
    // }
}

void ProtoClient::onConnection(const TcpConnectionPtr &conn) {
    LOG_INFO << conn->localAddress().toIpPort() << " -> "
             << conn->peerAddress().toIpPort() << " is "
             << (conn->connected() ? "UP" : "DOWN");
    {
        if (conn->connected()) {
            // MutexLockGuard lock(mutex_);
            connection_ = conn;
        } else {
            connection_.reset();
        }
    }
    if (!conn->connected()) {
        loop_->quit();
    }
}

void ProtoClient::onMessage(const TcpConnectionPtr &conn, Buffer *buf, Timestamp receiveTime) {
    string msg(buf->retrieveAllAsString());
    LOG_INFO << conn->name() << " client " << msg.size() << " bytes, "
             << "data received at " << receiveTime.toString();

    std::cout << "msg rec:" << msg << std::endl;
}


int main() {

    EventLoopThread loopThread;
    InetAddress serverAddr("127.0.0.1", 2007);
    ProtoClient client(loopThread.startLoop(), serverAddr);
    client.connect();
    // loop.loop();


    string msg("client test string @@ !!! woshi ");

    while (true) {
        if(client.getConectStatus()){
            client.sendMessage(msg);
            sleep(3);
            client.disconnect();
            break ;
        }
        usleep(10);
    }
}

